package com.shelpe.services.sinbad.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shelpe.services.sinbad.model.RptCreativeExample;
import com.shelpe.services.sinbad.model.RptCreativeExample.Criteria;
import com.shelpe.services.sinbad.service.RptCreativeService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("/sinbadservice/creatives")
public class CreativeController {

	static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd");
	
	@Autowired
	RptCreativeService rptCreativeService;
	
	/**
	 * 趋势图数据  .以日期分组
	 * @param creativeId
	 * @return
	 */
	@RequestMapping("/{creative_id}/reports/trend")
	public @ResponseBody Object reportsTrend(@PathVariable("creative_id") Long creativeId, 
			@RequestParam(defaultValue = "7")Integer days, @RequestParam(required = false)Integer device, 
			@RequestParam(required = false)String startDate, @RequestParam(required = false)String endDate){
		log.info("reportsTrend creativeId:{} days:{} device:{} startDate:{} endDate:{}", creativeId, days, device, startDate, endDate);
		RptCreativeExample example = new RptCreativeExample();
		Criteria criteria =  example.createCriteria();
		criteria.andCreativeIdEqualTo(creativeId);
		if(device!=null){
			switch (device) {
			case 1:
				criteria.andSourceBetween((byte)4, (byte)5);
				break;
			case 2:
				criteria.andSourceBetween((byte)1, (byte)2);
				break;
			}
		}
		if(!(startDate==null||endDate==null)){
			try {
				criteria.andDateBetween(SDF.parse(startDate), SDF.parse(endDate));
			} catch (ParseException e) {
				log.error("CreativeController reportsTrend:{}", e.getMessage());
			}
		}else{
			criteria.andDateGreaterThanOrEqualTo(getDate(new Date(), 0-days));
		}
		return rptCreativeService.getReportsTrend(example);
	}
	
	private Date getDate(Date date, int amount){
		Calendar calendar = Calendar.getInstance();
		if(date != null){
			calendar.setTime(date);
		}
		calendar.add(Calendar.DAY_OF_MONTH, amount);
		return calendar.getTime();
	}
}
